import { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import { getQuestionData } from "../service";
import { useRequest } from "ahooks";
import { useDispatch } from "react-redux";
import { resetComponent, ComponentStatetype } from "../store/componentReducer";
import { resetPageInfo } from "../store/pageInfoReducer";

function useGetQuestionData() {
  const dispatch = useDispatch();
  const { id = "" } = useParams();
  const { data, run, error, loading } = useRequest(
    async (id: string) => {
      if (!id) throw new Error("没有问卷ID....");
      const data = await getQuestionData(id);
      return data;
    },
    {
      manual: true,
    },
  );

  useEffect(() => {
    if (!data) return;
    const { title, desc, js, css, isPublish, componentList } = data;
    //获取默认的selectedid
    let selectedId = "";
    if (componentList.length > 0) {
      //默认选择第一个组件
      selectedId = componentList[0].fe_id;
    }
    dispatch(resetComponent({ componentList, selectedId: selectedId, copyComponent: null }));

    //保存页面信息
    dispatch(resetPageInfo({ title, desc, js, css, isPublish }));
  }, [data]);

  useEffect(() => {
    run(id);
  }, [id]);
  return { loading, error };
}

export default useGetQuestionData;
